import { ComputedRef, ref, watch } from "vue";
import { getPointDeg, getRotatePoint } from "/@/utils/draw";
import { CompCommon, Drag, DragMoveOptions, Point } from "/@/components/types";
import { useRotate } from "/@/hooks/useRotate";
import { SvgInfo } from "/@/Configuration/types";

interface UseDeviceRotateOptions {
  compCommon: CompCommon;
  centerPoint: ComputedRef<Point>;
  deviceId: string;
  getConnectPoints: () => Point[];
}
/**
 * 由包着svg图标的foreignObject元素触发的设备旋转,
 * @returns 旋转信息
 */
export function useDeviceRotate(options: UseDeviceRotateOptions) {
  //旋转带动连接点的前置数据
  let connData: Drag[] | undefined;
  let connectPoints: Point[] | undefined;
  //
  const { rotate, rotateStart } = useRotate({
    centerPoint() {
      return options.centerPoint.value;
    },
    getRelativeElement() {
      return (options.compCommon.getSvgInfo() as SvgInfo).container;
    },
    start() {
      connData = options.compCommon.connection.getConnect(options.deviceId);
      connectPoints = options.getConnectPoints();
    },
    end() {
      connData = void 0;
      connectPoints = void 0;
    },
  });
  watch(rotate, (deg) => {
    let isReset = false;
    if (!connData || !connectPoints) {
      //说明是由直接设置rotate的值触发的旋转，而不是由点击用户点击旋转图标触发的旋转
      isReset = true;
      connData = options.compCommon.connection.getConnect(options.deviceId);
      connectPoints = options.getConnectPoints();
    }
    //如果有连接管道 则带动所有连接点一起旋转
    if (connData && connectPoints) {
      for (let i = 0; i < connData.length; i++) {
        const drag = connData[i];
        const moveOptions: DragMoveOptions = {};
        if (drag.extra && drag.extra.connectPositionIndex !== undefined) {
          const connectPoint = connectPoints[drag.extra.connectPositionIndex] || connectPoints[0];
          //getRotatePoint核心方法
          const rotateConnectPoint = getRotatePoint(options.centerPoint.value, connectPoint, deg);
          moveOptions.x = rotateConnectPoint.x;
          moveOptions.y = rotateConnectPoint.y;
          drag.move(moveOptions);
        }
      }
      if (isReset) {
        //由直接设置rotate的值触发的旋转需要重置前置数据
        connData = void 0;
        connectPoints = void 0;
      }
    }
  });
  return {
    rotateStart,
    rotate,
  };
}
